package org.liubility.server.security.service;

import lombok.extern.slf4j.Slf4j;
import org.liubility.security.service.AuthUserEntity;
import org.liubility.server.usersys.entity.User;
import org.liubility.server.usersys.service.RoleService;
import org.liubility.server.usersys.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: Jdragon
 * @email: 1061917196@qq.com
 * @Date: 2020.03.19 23:23
 * @Description: 使UserDetail与数据库交互
 */
@Slf4j
@Service
public class AuthUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;
    /**
     * 通过账号查找用户、角色的信息
     * @param name
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
        User user = userService.getUserByName(name);
        if (user == null) {
            throw new UsernameNotFoundException(String.format("%s.这个6用户不存在", name));
        }else {
            //查找角色
            List<String> roles =  roleService.getRolesByUsername(name);
            List<SimpleGrantedAuthority> authorities = new ArrayList<>();
            for (String role : roles) {
                authorities.add(new SimpleGrantedAuthority(role));
            }
            log.debug("loadUserByUsername.....user ===> " + user);
            return new AuthUserEntity(user.getUsername(),user.getPassword(), authorities);
        }
    }
}
